const express = require('express');
const router = express.Router();
const multer = require('multer');
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'public/uploads/')
  },
  filename: (req, file, cb) => {
    // 处理中文文件名乱码问题
    const originalname = Buffer.from(file.originalname, 'latin1').toString('utf8')
    cb(null, Date.now() + '-' + originalname)
  }
})

// 限制文件大小为5MB
const upload = multer({ storage, limits: { fileSize: 5 * 1024 * 1024 }  })
/**
 * @typedef {FormData} file
 * @property {Buffer} file - 要上传的文件
 * @property {string} [filename] - 可选文件名
 */
/**
 * POST /api/upload
 * @security BearerAuth
 * @header {string} Authorization - Bearer Token 认证信息，格式为: Bearer {token}
 * @summary 上传文件至服务器
 * @tags upload
 * @consumes multipart/form-data
 * @param {file} request.body.formData - 上传的文件
 * @return {object} 200 - 上传成功，返回文件信息
 */
router.post('/upload', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({
      code: 400,
      message: '未找到上传的文件'
    });
  }
  
  // 构建文件访问URL（根据实际部署情况调整）
  const fileUrl = req.file.path.replace('public', '').replaceAll('\\', '/');
  res.status(200).json({
    code: 200,
    data: fileUrl,
    message: '文件上传成功'
  });
});

module.exports = router;
